DataStorage   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 4
eloc 28
dl 0
loc 32
ccs 13
cts 13
cp 1
rs 10
c 0
b 0
f 0

3 Functions

Rating   Name   Duplication   Size   Complexity  
A attach 0 7 1
A loadData 0 9 2
A updateStorage 0 3 1
1
import {ObserverAdapter, OnChangeCallback} from '@enbock/state-value-observer/ValueObserver';
2
import StorageAdapter from './StorageAdapter';
3
4
export interface AdapterDictionary {
5
  [index: string]: StorageAdapter<any>
6
}
7
8
export default class DataStorage {
9
  protected domain: string;
10
  protected storage: Storage;
11
  protected adapters: AdapterDictionary;
12
13
  constructor(domain: string, storage: Storage) {
14 3
    this.domain = domain;
15 3
    this.storage = storage;
16 3
    this.adapters = {};
17
  }
18
19
  attach<Type>(key: string, adapter: ObserverAdapter<Type>): StorageAdapter<Type> {
20 1
    const callback: OnChangeCallback<Type> = (newValue: Type) => this.updateStorage(key, newValue);
21 1
    const storageAdapter: StorageAdapter<Type> = new StorageAdapter<Type>(adapter, callback);
22 1
    this.adapters[key] = storageAdapter;
23
24 1
    return storageAdapter;
25
  }
26
27
  loadData<Type>(key: string, initialValue: Type): Type {
28 2
    const serializedJsonData: string | null = this.storage.getItem(this.domain + '::' + key);
29 2
    let data: Type = initialValue;
30 2
    if (serializedJsonData != null) {
31 1
      data = JSON.parse(serializedJsonData) as Type;
32
    }
33
34 2
    return data;
35
  }
36
37
  protected updateStorage<Type>(key: string, newValue: Type) {
38 1
    this.storage.setItem(this.domain + '::' + key, JSON.stringify(newValue));
39
  }
40
}
41